package com.dg11185.nearshop.activity.home;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.HeaderViewListAdapter;
import android.widget.ListAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.android.nearshop.R;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.network.http.client.HttpRequest.ActionListener;
import com.dg11185.nearshop.activity.SubPageActivity;
import com.dg11185.nearshop.activity.shop.ShopDetailActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.Utils;
import com.dg11185.nearshop.net.request.GetDayMerListRequest;
import com.dg11185.nearshop.net.response.GetDayMerListResponse;
import com.dg11185.nearshop.view.adapter.V_ShopListAdapter;
import com.dg11185.nearshop.view.xlistview.XListView;
import com.dg11185.nearshop.view.xlistview.XListView.IXListViewListener;
import com.wlper.lib.uitls.LogUtils;
import com.wlper.lib.uitls.ViewUtils;
import com.wlper.lib.view.loading.BaseLoadLayout.LoadStateHandler;
import com.wlper.lib.view.loading.LoadLayoutWithFrameAnim;

/**
 * 特惠日商家子界面。点击按钮和手势切换都可以控制页面切换
 * 
 * @author wanliang527
 * @date 2014-5-9
 * 
 */
public class DayShopsActivity extends SubPageActivity {
    private final static String DG_AREA_NUM = "0001900017";
    private final static int PAGE_SIZE = 25;

    private RadioGroup mRadioGroup;
    private ViewPager mViewPager;

    private Handler mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_all_day_shops);
        initView();
    }

    private OnCheckedChangeListener checkedListener = new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            View checkedView = findViewById(checkedId);

            String tag = null;
            String curPage = null;
            if (checkedView != null)
                tag = (String) checkedView.getTag();
            if (mViewPager != null)
                curPage = (mViewPager.getCurrentItem() + 1) + "";
            if (tag == null || tag.equals(curPage)) {
                return;
            }

            boolean isSmoothScroll = false;
            switch (checkedId) {
                case R.id.ra_btn_mon:
                    mViewPager.setCurrentItem(0, isSmoothScroll);
                    break;
                case R.id.ra_btn_tues:
                    mViewPager.setCurrentItem(1, isSmoothScroll);
                    break;
                case R.id.ra_btn_wed:
                    mViewPager.setCurrentItem(2, isSmoothScroll);
                    break;
                case R.id.ra_btn_thur:
                    mViewPager.setCurrentItem(3, isSmoothScroll);
                    break;
                case R.id.ra_btn_fri:
                    mViewPager.setCurrentItem(4, isSmoothScroll);
                    break;
                case R.id.ra_btn_sat:
                    mViewPager.setCurrentItem(5, isSmoothScroll);
                    break;
                case R.id.ra_btn_sun:
                    mViewPager.setCurrentItem(6, isSmoothScroll);
                    break;
            }

        }
    };

    private OnPageChangeListener pageListener = new OnPageChangeListener() {

        int[] radioBtnIds = new int[] { R.id.ra_btn_mon, R.id.ra_btn_tues,
                R.id.ra_btn_wed, R.id.ra_btn_thur, R.id.ra_btn_fri,
                R.id.ra_btn_sat, R.id.ra_btn_sun };

        @Override
        public void onPageSelected(int arg0) {
            int checkedId = mRadioGroup.getCheckedRadioButtonId();
            if (checkedId == radioBtnIds[arg0])
                return;

            ((RadioButton) findViewById(radioBtnIds[arg0])).setChecked(true);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    };

    private void initView() {
        findViewsId();
        setSubPageTitle("特惠日优惠");
        mViewPager.setAdapter(new MpagerAdapter(this));
        mViewPager.setOnPageChangeListener(pageListener);
        mRadioGroup.setOnCheckedChangeListener(checkedListener);
        check(Utils.getWeek());
    }

    private void check(int pos) {
        if (pos == 1) {
            ((RadioButton) findViewById(R.id.ra_btn_mon)).setChecked(true);
            // mRadioGroup.check(R.id.ra_btn_mon);
        } else if (pos == 2) {
            ((RadioButton) findViewById(R.id.ra_btn_tues)).setChecked(true);
            // mRadioGroup.check(R.id.ra_btn_tues);
        } else if (pos == 3) {
            ((RadioButton) findViewById(R.id.ra_btn_wed)).setChecked(true);
            // mRadioGroup.check(R.id.ra_btn_wed);
        } else if (pos == 4) {
            ((RadioButton) findViewById(R.id.ra_btn_thur)).setChecked(true);
            // mRadioGroup.check(R.id.ra_btn_thur);
        } else if (pos == 5) {
            ((RadioButton) findViewById(R.id.ra_btn_fri)).setChecked(true);
            // mRadioGroup.check(R.id.ra_btn_fri);
        } else if (pos == 6) {
            ((RadioButton) findViewById(R.id.ra_btn_sat)).setChecked(true);
            // mRadioGroup.check(R.id.ra_btn_sat);
        } else if (pos == 7) {
            ((RadioButton) findViewById(R.id.ra_btn_sun)).setChecked(true);
            // mRadioGroup.check(R.id.ra_btn_sun);
        }
    }

    private void findViewsId() {
        mRadioGroup = (RadioGroup) findViewById(R.id.ra_group);
        mViewPager = (ViewPager) findViewById(R.id.v_pager);
    }

    private class MpagerAdapter extends PagerAdapter {
        private Context mContext;
        private ArrayList<View> viewList = new ArrayList<View>();
        private SparseArray<List<Map<String, Object>>> allData = new SparseArray<List<Map<String, Object>>>();

        public MpagerAdapter(Context context) {
            super();
            mContext = context;
            LayoutInflater inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            for (int i = 0; i < 7; i++) {
                View view = inflater.inflate(R.layout.view_shops_on_vip_day,
                        null);
                ViewStub viewStub = (ViewStub) view
                        .findViewById(R.id.stub_list2);
                viewStub.inflate();
                view.findViewById(R.id.label_vip_day).setVisibility(View.GONE);
                view.findViewById(R.id.btn_more_vip_shops).setVisibility(
                        View.GONE);
                viewList.add(view);
            }
        }

        @Override
        public int getCount() {
            return viewList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(viewList.get(position));
        }

        private String convert(int position) {
            if (position == 6) {
                return "0";
            } else {
                return (position + 1) + "";
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            final View view = viewList.get(position);
            final XListView list = (XListView) view
                    .findViewById(R.id.list_v_shops1);
            final LoadLayoutWithFrameAnim loadingView = (LoadLayoutWithFrameAnim) view
                    .findViewById(R.id.flayout_shops_on_vd);
            onGetDayMerList(view, position);

            list.setPullRefreshEnable(false);
            list.stopLoadMore();
            if (list.getXListViewListener() == null) {
                list.setXListViewListener(new IXListViewListener() {
                    @Override
                    public void onRefresh() {
                    }

                    @Override
                    public void onLoadMore() {
                        onGetDayMerList(view, position);
                    }
                });
            }
            // 设置重加载事件
            if (loadingView.getStateHandler() == null) {
                loadingView.setStateHandler(new LoadStateHandler() {
                    @Override
                    public void onReload() {
                        onGetDayMerList(view, position);
                    }

                    @Override
                    public void onLoading() {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onLoadFailed() {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onLoadSuccess() {
                        // TODO Auto-generated method stub

                    }
                });
            }
            list.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                        int position, long id) {
                    // 点击会员日商家的事件处理
                    V_ShopListAdapter.ViewHolder viewHolder = (V_ShopListAdapter.ViewHolder) view
                            .getTag();
                    Intent intent = new Intent(mActivity,
                            ShopDetailActivity.class);
                    intent.putExtra("merchant_id", viewHolder.merchantId);
                    startActivity(intent);

                }
            });
            container.addView(view);
            return view;
        }

        private void onGetDayMerList(final View view, final int position) {
            final XListView list = (XListView) view
                    .findViewById(R.id.list_v_shops1);
            final LoadLayoutWithFrameAnim loadingView = (LoadLayoutWithFrameAnim) view
                    .findViewById(R.id.flayout_shops_on_vd);

            // 显示加载状态
            if (!loadingView.isLoading())
                loadingView.onLoading();
            PageViewExtra extra = null;
            if (view.getTag() == null
                    || !(view.getTag() instanceof PageViewExtra)) {
                extra = new PageViewExtra();
                view.setTag(extra);
            }
            extra = (PageViewExtra) view.getTag();
            if (extra.index != 0 && extra.index >= extra.counts) {
                // *******服务端没有数据的情况下，作以下处理***********//
                // ListView屏蔽掉上拉加载更多的功能
                list.setPullLoadEnable(false);
                if (loadingView.isLoading())
                    loadingView.onLoadSuccess();
                // 如果该日的会员日商家已经加载完了，就不再进行联网加载了
                if (position < allData.size() && allData.get(position) != null) {
                    // 从内存中查找是否存在已有的数据，如果有的话，直接取出来显示
                    if (list.getAdapter() == null) {
                        list.setAdapter(new V_ShopListAdapter(mContext, allData
                                .get(position)));
                    }
                }
                return;
            } else {
                GetDayMerListRequest req = new GetDayMerListRequest();
                req.add(GetDayMerListRequest.AREA_NUM, DG_AREA_NUM);
                req.add(GetDayMerListRequest.PAGE_NUM, ++extra.curPage + "");
                req.add(GetDayMerListRequest.PAGE_SIZE, PAGE_SIZE + "");
                req.add(GetDayMerListRequest.WEEK, convert(position));
                req.encryption();
                req.setActionListener(new ActionListener<GetDayMerListResponse>() {
                    @Override
                    public void onSuccess(GetDayMerListResponse result) {
                        LogUtils.logNetReturn(Constants.getDayMerList,
                                result.responseStr);
                        list.stopLoadMore();
                        if (result.statusStr.equals("SUCCESS")) {
                            loadingView.onLoadSuccess();
                            updateView(view, result, position);
                        } else {
                            ViewUtils.showToast(mActivity,
                                    R.string.network_error);
                            LogUtils.logNetError("获取会员日商家失败---"
                                    + result.statusStr);
                            loadingView.onLoadFailed();
                        }
                    }

                    @Override
                    public void onFailure(int resultCode) {
                        LogUtils.logNetError("获取会员日商家失败---" + resultCode);
                        if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                            ViewUtils.showToast(mActivity,
                                    R.string.cant_connect_network);
                        } else {
//                            ViewUtils.showToast(mActivity,
//                                    R.string.network_error);
                        }
                        loadingView.onLoadFailed();
                        list.stopLoadMore();
                    }

                });

                NetClient.httpPost(req);

            }
        }

        private void updateView(View view, GetDayMerListResponse result,
                int position) {
            final XListView list = (XListView) view
                    .findViewById(R.id.list_v_shops1);
            PageViewExtra extra = view.getTag() == null ? null
                    : (PageViewExtra) view.getTag();
            if (extra != null) {
                extra.counts = Integer.valueOf(result.total);
                if (extra.counts > 0) {
                    int retCounts = result.dayMerList.size();
                    extra.index = extra.index + retCounts;

                    List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
                    for (int i = 0; i < retCounts; i++) {
                        Map<String, Object> map = new HashMap<String, Object>();
                        map.put("coverUrl",
                                result.dayMerList.get(i).midPhotoUrl);
                        map.put("name", result.dayMerList.get(i).merchantName);
                        map.put("disContent",
                                result.dayMerList.get(i).preferential);
                        map.put("discount",
                                HomeFragment2.getDiscountType(result.dayMerList
                                        .get(i).preferentialType));
                        map.put("merchantId",
                                result.dayMerList.get(i).merchantId);
                        data.add(map);
                    }
                    // 将数据缓存到内存中
                    allData.append(position, data);
                    ListAdapter adapter = list.getAdapter();
                    if (adapter == null) {
                        adapter = new V_ShopListAdapter(mActivity, data);
                        list.setAdapter(adapter);
                    } else {
                        if (adapter instanceof HeaderViewListAdapter) {
                            HeaderViewListAdapter adapter2 = (HeaderViewListAdapter) adapter;
                            updateAdapterData(
                                    (V_ShopListAdapter) adapter2.getWrappedAdapter(),
                                    data);
                        } else {
                            updateAdapterData((V_ShopListAdapter) adapter, data);
                        }

                    }
//                    V_ShopListAdapter adapter = (V_ShopListAdapter) list
//                            .getAdapter();
//                    if (adapter == null) {
//                        adapter = new V_ShopListAdapter(mActivity, data);
//                        list.setAdapter(adapter);
//                    } else {
//                        adapter.getData().addAll(data);
//                        adapter.notifyDataSetChanged();
//                    }

                    // ListView重新绘制好数据后，在重新判断是否要开启上拉加载更多的功能
                    if (list.getVisibleItemCount() < list.getTotalItemCount()) {
                        list.setPullLoadEnable(true);
                    } else {
                        list.setPullLoadEnable(false);
                    }
                }

            }
        }
        
        private void updateAdapterData(V_ShopListAdapter adapter,
                List<Map<String, Object>> data) {
            adapter.getData().addAll(data);
            adapter.notifyDataSetChanged();
        }
    }

    class PageViewExtra {
        private int counts = 0;
        private int index = 0;
        private int curPage = 0;
    }

    public void onListRefresh(final XListView view) {
        if (mHandler == null) {
            mHandler = new Handler();
        }
        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                ViewUtils.showToast(getApplicationContext(), "加载更多");
                updateListView(view);
            }
        }, 2000);
    }

    public void onListLoadMore(final XListView view) {
        if (mHandler == null) {
            mHandler = new Handler();
        }
        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                ViewUtils.showToast(getApplicationContext(), "加载更多");
                updateListView(view);
            }
        }, 2000);
    }

    private void updateListView(XListView view) {
        view.stopLoadMore();
        view.stopRefresh();
        view.setRefreshTime(Utils.getTime(new SimpleDateFormat(
                "yyyy年MM月dd日  HH:mm")));
    }

}
